package com.handu.luna.boss.controller;


import com.handu.luna.core.domain.goods.Goods;
import com.handu.luna.core.domain.promotion.Promotion;
import com.handu.luna.core.domain.promotion.Topic;
import com.handu.luna.core.domain.promotion.TopicModule;
import com.handu.luna.core.domain.search.TopicSearch;
import com.handu.luna.core.domain.searchVo.GoodsSearch;
import com.handu.luna.core.domain.support.FileUploadSupport;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.List;

@Controller
@RequestMapping("/promotion/topic/*")
public class TopicController extends BaseController {

	@RequestMapping(value = "index",method = RequestMethod.GET)
    public BossModel index(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException {

        TopicSearch topicSearch;
        BossModel bossModel = createModel("promotion/topic/index");
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			topicSearch = (TopicSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState),"UTF-8")), TopicSearch.class);
		}else{
			topicSearch = new TopicSearch();
            viewState = "";
		}
        return bossModel.add("topicPage",context.getTopicRepository().findAll(Topic.selectCondition(topicSearch),pageable))
                .add("topicSearch",topicSearch)
                .add("statusValues", Promotion.PromotionStatus.values())
                .add("viewState", viewState);
	}

    @RequestMapping(value = "index",method = RequestMethod.POST)
    public BossModel index(TopicSearch topicSearch,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException {
        BossModel bossModel = createModel();
        return bossModel.add("topicPage",context.getTopicRepository().findAll(Topic.selectCondition(topicSearch),pageable))
                .add("topicSearch",topicSearch)
                .add("statusValues", Promotion.PromotionStatus.values())
                .add("viewState",Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(topicSearch).toString().getBytes("UTF-8")));
	}

    @RequestMapping(value = "add",method = RequestMethod.GET)
    public BossModel add() {

        return createModel("/promotion/topic/info").add("topic",new Topic());
    }

    @RequestMapping(value = "edit/{id}",method = RequestMethod.GET)
    public BossModel edit(@PathVariable Long id) {

        Topic topic = context.getTopicRepository().findOne(id);

        return createModel("/promotion/topic/info").add("topic",topic);

    }

    @InitBinder(value = {"name","fileName","url","startDate","endDate","imgFile","displayOrder","keywords","description","templateFile"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public BossModel save(@Valid Topic topic,BindingResult bindingResult,int step
    ,@RequestParam("uploadfile1") MultipartFile file1,@RequestParam("uploadfile2") MultipartFile file2) {

        if(StringUtils.isNotBlank(file1.getOriginalFilename())) {
            String fileName = file1.getOriginalFilename();
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
            if(!(ext.equals("jpg") || ext.equals("jpeg") || ext.equals("png") || ext.equals("jpg") ||ext.equals("gif") || ext.equals("ico"))) {
                topic.setImgFile(null);
                bindingResult.rejectValue("imgFile", "", "请上传图片文件");
            }else {
                try {
                    topic.setImgFile(FileUploadSupport.upload(file1.getInputStream(), file1.getOriginalFilename(), FileUploadSupport.ImageType.TOPIC));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (StringUtils.isNotBlank(file2.getOriginalFilename())) {
            try {
                topic.setTemplateFile(FileUploadSupport.upload(file2.getInputStream(), file2.getOriginalFilename(), FileUploadSupport.ImageType.TOPIC));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if(StringUtils.isBlank(topic.getImgFile()) && StringUtils.isBlank(file1.getOriginalFilename())) {
            topic.setImgFile(null);
            bindingResult.rejectValue("imgFile", "", "请上传图片文件");
        }

        if(StringUtils.isBlank(topic.getTemplateFile()) && StringUtils.isBlank(file2.getOriginalFilename())) {
            topic.setTemplateFile(null);
            bindingResult.rejectValue("templateFile", "", "请上传模板文件");
        }

        if(null == topic.getStartDate()) {
            bindingResult.rejectValue("startDate","","开始时间不能为空");
        }
        if(null == topic.getEndDate()) {
            bindingResult.rejectValue("endDate","","结束时间不能为空");
        }
        if(null != topic.getStartDate() && null != topic.getEndDate()) {
            if(topic.getStartDate().compareTo(topic.getEndDate()) != -1) {
                bindingResult.rejectValue("startDate","","开始时间必须小于结束时间");
            }
        }

        if(bindingResult.hasErrors()) {
            topic.setStep(1);
            return createModel("/promotion/topic/info").add("topic",topic);
        }

        if (StringUtils.isNotBlank(file2.getOriginalFilename())) {
            try {
                topic.setTemplateFile(FileUploadSupport.upload(file2.getInputStream(), file2.getOriginalFilename(), FileUploadSupport.ImageType.TOPIC));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String message = null;

        if(topic.isNew()) {
            topic = context.getTopicRepository().save(topic);
            message = "添加 专题活动 成功";
        }else {
            topic = topic.update();
        }
        topic.setStep(step);

        return getEditModel(topic,message);
    }

    @RequestMapping(value = "updateContent", method = RequestMethod.POST)
    public BossModel updateContent(long id,int step,String content) {

        Topic topic = context.getTopicRepository().findOne(id);
        topic.setContent(content);
        topic.update();
        topic.setStep(step);

        return getEditModel(topic,null);
    }

    @RequestMapping(value = "updateModules", method = RequestMethod.POST)
    public BossModel updateModules(int step,Topic topic) {

        //判断删除的列表 如果不为空 则删除对应的模块 并删除模块和专题的关系
        if(CollectionUtils.isNotEmpty(topic.getDeleteIdList())) {
            for(long deleteId : topic.getDeleteIdList()) {
                context.getTopicModuleRepository().delete(deleteId);
            }
        }

       /* //获取要更新的模块信息
        List<TopicModule> topicModuleList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(topic.getTopicModuleList())) {
            topicModuleList = topic.getTopicModuleList();

        }*/
        topic.updateTopicModules();
//        topic = context.getTopicRepository().findOne(topic.getId());
//        //获取修改模块的商品信息
//        for(TopicModule topicModule : topicModuleList) {
//            if(!topicModule.isNew()) {
//                TopicModule tempTopicModule = context.getTopicModuleRepository().findOne(topicModule.getId());
//                if(tempTopicModule != null) {
//                     if(tempTopicModule.getGoodsList() != null) {
//                     topicModule.setGoodsList(tempTopicModule.getGoodsList());
//                    }
//                    if(tempTopicModule.getGoodsIdList() != null) {
//                        topicModule.setGoodsIdList(tempTopicModule.getGoodsIdList());
//                    }
//                }
//
//            }
//        }
//        topic.setTopicModuleList(topicModuleList);
//
//        topic = topic.update();
        topic.setStep(step);

        return getEditModel(topic,null);
    }

    @RequestMapping(value = "updateGoods", method = RequestMethod.POST)
    public BossModel updateGoods(int step, Topic topic,RedirectAttributes redirectAttributes) {

        //Topic oldTopic = context.getTopicRepository().findOne(topic.getId());
       /* if (CollectionUtils.isNotEmpty(oldTopic.getTopicModuleList())) {
            //获取页面传递的多个GoodsIdList
            List<TopicModule> topicModuleList;
            List<List<Long>> allGoodsIdList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(topic.getTopicModuleList())) {
                topicModuleList = topic.getTopicModuleList();
                for (TopicModule topicModule : topicModuleList) {
                    allGoodsIdList.add(topicModule.getGoodsIdList());
                }
            }
            int newSize = allGoodsIdList.size();

            //获取不能修改的TopicModuleList
            topic = context.getTopicRepository().findOne(topic.getId());
            int oldSize = topic.getTopicModuleList().size();

            //创建没有添加商品的goodsIdList
            if ((oldSize - newSize) > 0) {
                for (int i = 0; i < oldSize - newSize; i++) {
                    allGoodsIdList.add(new ArrayList<>());
                }
            }

            //为不能修改的TopicModuleList设置商品
            for (int i = 0; i < topic.getTopicModuleList().size(); i++) {
                TopicModule topicModule = topic.getTopicModuleList().get(i);
                topicModule.setGoodsIdList(allGoodsIdList.get(i));
                topicModule.update();
            }
        }*/

        topic.updateGoods();

        topic.setStep(step);

        if(topic.getStep() == 5) {
            redirectAttributes.addFlashAttribute("message","修改 专题活动 成功");
            return createModel("redirect:index");
        }else {
             return getEditModel(topic,null);
        }
    }



    @RequestMapping(value = "goodsSearch",method = RequestMethod.POST)
    public @ResponseBody JSONArray goodsSearch(String goodsCategoryId,String goodsBrandsId,String goodsName){

        GoodsSearch goodsSearch = new GoodsSearch();
        goodsSearch.setGoodsCategoryId(goodsCategoryId);
        goodsSearch.setGoodsBrandsId(goodsBrandsId);
        goodsSearch.setKeyword(goodsName);

        List<Goods> list = context.getGoodsRepository().findAll(Goods.topicSearchGoods(goodsSearch));
        StringBuffer buffer = new StringBuffer("[");
        if(CollectionUtils.isNotEmpty(list)){
            for (Goods goods:list){
                buffer.append("{\"id\":\""+goods.getId()+"\",\"name\":\""+goods.getName()+"\"},");
            }
        }
        if (buffer.length()>1){
            buffer.deleteCharAt(buffer.length()-1);
        }
        buffer.append("]");
        return JSONArray.fromObject(buffer.toString());
    }



    private BossModel getEditModel(Topic topic,String message) {
        BossModel bossModel;
        switch (topic.getStep()) {
            case 1:
                bossModel = createModel("/promotion/topic/info");
                break;
            case 2:
                bossModel = createModel("/promotion/topic/content");
                break;
            case 3:
                bossModel = createModel("/promotion/topic/topicmodule")
                            .add("adPositionList",context.getAdPositionIdRepository().findAll());
                break;
            case 4:
                bossModel = createModel("/promotion/topic/goods")
                            .add("brandList", context.getBrandRepository().findAll())
                            .add("categoryList", context.getCategoryRepository().findAll());
                break;
            case 5:
                bossModel = createModel("redirect:index");
                break;
            default:
                bossModel = createModel("/promotion/topic/info");
        }

        if(null == topic.getId()) {
            topic = new Topic();
        }else {
            topic = context.getTopicRepository().findOne(topic.getId());
        }
        if(message != null) {
            bossModel.add("message",message);
        }else{
            bossModel.add("message","修改 专题活动 成功");
        }

        return bossModel.add("topic",topic);
    }
	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(String viewState,long id,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable){

        Topic topic = context.getTopicRepository().findOne(id);
        if(CollectionUtils.isNotEmpty(topic.getTopicModuleList())) {
            for(TopicModule topicModule : topic.getTopicModuleList()) {
                context.getTopicModuleRepository().delete(topicModule);
            }
        }
		context.getTopicRepository().delete(id);
 
 		return createModel("promotion/topic/topic_table")
                .add("topicPage",context.getTopicRepository().findAll(pageable))
                .add("viewState",viewState);

	}

    @RequestMapping(value="verifyFileName")
	public @ResponseBody boolean verifyFileName(Topic topic){

		int num = context.getTopicRepository().findByFileName(topic.getFileName()).size();
		if(num != 0){
			if(topic.getId() != null) {
                if(context.getTopicRepository().findOne(topic.getId()).getFileName().equals(topic.getFileName())){
                    return true;
                }else {
                    return false;
                }
            }else {
                return false;
            }
		}else{
			return true;
		}
	}



}
